<template>
  <div 
    :id="id"
    :class="['draggable-item', { 'selected': isSelected }]"
    @click.stop="handleSelect"
    draggable="true"
    @dragstart="handleDragStart"
    @dragover.prevent="handleDragOver"
    @drop.stop="handleDrop"
  >
    <!-- 组件本身 -->
    <FormProvider :form="form" :key="formKey" v-if="showSchema">
      <SchemaField :schema="schema" :key="schemaKey" />
    </FormProvider>

    <!-- 容器组件的子组件区域 -->
    <div v-if="isContainer" 
      class="container-wrapper"
      :class="containerClass"
    >
      <template v-for="child in childComponents" :key="child.id">
        <DraggableItem
          :id="child.id"
          :configData="child.configData"
        />
      </template>
      <div v-if="childComponents.length === 0" class="empty-tip">
        拖拽组件到这里
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick } from 'vue';
import { createForm } from '@formily/core';
import { FormProvider, createSchemaField } from '@formily/vue';
import { 
  Input,
  Password,
  InputNumber,
  Select,
  TreeSelect,
  Cascader,
  DatePicker,
  TimePicker,
  Checkbox,
  Radio,
  Upload,
  FormGrid,
  Space,
  ArrayTable,
  ArrayCards,
  FormItem
} from '@formily/antdv-x3';
import { Rate, Slider } from 'ant-design-vue';
import { useEditorStore } from '@/stores/editor';

const props = defineProps<{
  id: string;
  configData: any;
}>();

const editorStore = useEditorStore();
const form = ref(createForm());
const schemaKey = ref(0);
const formKey = ref(0);
const showSchema = ref(true);
// 注册组件
const { SchemaField } = createSchemaField({
  components: {
    Input,
    Password,
    InputNumber,
    Select,
    TreeSelect,
    Cascader,
    DatePicker,
    TimePicker,
    Checkbox,
    Radio,
    Upload,
    FormGrid,
    Space,
    ArrayTable,
    ArrayCards,
    FormItem,
    'a-rate': Rate,
    'a-slider': Slider
  },
});

// 判断是否是容器组件
const isContainer = computed(() => 
  ['FormGrid', 'Space', 'ArrayTable', 'ArrayCards'].includes(props.configData.field)
);

// 获取子组件
const childComponents = computed(() => 
  editorStore.canvasComponents.filter(comp => 
    comp.parentId === props.id
  )
);

// 处理拖拽开始
const handleDragStart = (event: DragEvent) => {
  if (event.dataTransfer) {
    // 找到当前组件的完整数据
    const component = editorStore.canvasComponents.find(c => c.id === props.id);
    if (component) {
      // 传递完整的组件数据
      event.dataTransfer.setData('json/plain', JSON.stringify({
        ...component,
        id: component.configData.id // 重置 ID 以便创建新组件
      }));
      editorStore.setDraggingId(props.id);
    }
  }
};

// 处理拖拽悬停
const handleDragOver = (event: DragEvent) => {
  if (isContainer.value) {
    event.preventDefault();
    const el = event.currentTarget as HTMLElement;
    el.classList.add('drag-over');
  }
};

// 处理放置
const handleDrop = (event: DragEvent) => {
  if (!isContainer.value) return;
  
  event.preventDefault();
  event.stopPropagation();
  
  const el = event.currentTarget as HTMLElement;
  el.classList.remove('drag-over');
  
  const configData = event.dataTransfer?.getData('json/plain');
  if (!configData) return;
  
  try {
    const componentData = JSON.parse(configData);
    const draggingId = editorStore.draggingId;
    
    if (draggingId) {
      // 如果是已有组件，则移动到新容器
      editorStore.moveComponent(draggingId, props.id);
    } else {
      // 如果是新组件，则添加到容器
      editorStore.addComponent(componentData, props.id);
    }
  } catch (error) {
    console.error('Error handling drop:', error);
  }
};

// 组件选择
const isSelected = computed(() => editorStore.selectedComponentId === props.id);

const handleSelect = () => {
  console.log('props.configData.config', props.id);
  editorStore.selectComponent(props.id);
};

// 更新配置
const updateConfig = () => {
  props.configData.config = { ...props.configData.config };
  showSchema.value = false;
  nextTick(() => {
    schemaKey.value += 1;
    formKey.value += 1;
    showSchema.value = true;
  });
};

// 监听配置变化
watch(() => props.configData.config, (newConfig) => {
  showSchema.value = false;
  nextTick(() => {
    schemaKey.value += 1;
    formKey.value += 1;
    showSchema.value = true;
  });
}, { deep: true });

// schema 配置
const schema = computed(() => ({
  type: 'object',
  properties: {
    [props.id]: props.configData.config
  }
}));

// 合并组件样式
const componentStyle = computed(() => ({
  ...props.configData.config['x-component-props']?.style,
  ...props.configData.style
}));

// 容器组件的属性
const containerProps = computed(() => {
  const componentProps = props.configData.config['x-component-props'] || {};
  
  switch (props.configData.field) {
    case 'FormGrid':
      return {
        ...componentProps,
        maxColumns: componentProps.maxColumns || 3,
        minColumns: componentProps.minColumns || 1,
        columnGap: componentProps.columnGap || 8,
        rowGap: componentProps.rowGap || 4
      };
    case 'Space':
      return {
        ...componentProps,
        size: componentProps.size || 'small',
        direction: componentProps.direction || 'horizontal',
        wrap: true
      };
    case 'ArrayTable':
      return {
        ...componentProps,
        bordered: true,
        style: { width: '100%' }
      };
    case 'ArrayCards':
      return {
        ...componentProps,
        style: { width: '100%' }
      };
    default:
      return componentProps;
  }
});

// 容器类名
const containerClass = computed(() => ({
  'form-grid-container': props.configData.field === 'FormGrid',
  'space-container': props.configData.field === 'Space',
  'array-table-container': props.configData.field === 'ArrayTable',
  'array-cards-container': props.configData.field === 'ArrayCards'
}));

const selectedComponent = computed(() => editorStore.canvasComponents.find(c => c.id === editorStore.selectedComponentId));
console.log('selectedComponent', selectedComponent.value);

watch(selectedComponent, (newComponent) => {
  if (newComponent) {
    form.value.setValues({
      ...newComponent.configData.config,
      style: newComponent.style || {}, // 确保这里包含了高度
      events: newComponent.events || {}
    });
  }
});
</script>

<style lang="less" scoped>
.draggable-item {
  position: relative;
  width: 100%;
  margin-bottom: 12px;
  cursor: move;
  
  &.selected {
    outline: 2px solid #1890ff;
  }

  &.drag-over {
    border-color: #1890ff;
    background-color: rgba(24, 144, 255, 0.1);
  }

  // 表单项样式
  :deep(.ant-formily-item) {
    margin-bottom: 0;
    width: 100%;
  }

  // 输入框样式
  :deep(.ant-input),
  :deep(.ant-input-number),
  :deep(.ant-select),
  :deep(.ant-picker) {
    width: 100%;
  }
}

// 容器组件样式
.container-wrapper {
  min-height: 100px;
  padding: 16px;
  background: #fafafa;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  transition: all 0.3s;

  &.form-grid-container {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px;
    padding: 16px;

    .draggable-item {
      margin-bottom: 0;
    }
  }

  &.space-container {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    padding: 16px;

    .draggable-item {
      margin-bottom: 0;
      flex: 0 0 auto;
    }
  }

  .empty-tip {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100px;
    color: #999;
    font-size: 14px;
  }
}

// 根据组件类型应用不同的宽度
:deep {
  .ant-input-number,
  .ant-select,
  .ant-cascader-picker,
  .ant-picker,
  .ant-input-password {
    width: 100%;
  }

  .ant-radio-group,
  .ant-checkbox-group {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }

  .ant-upload-wrapper {
    width: 100%;
  }
}
</style>
